package org.aplikator.client.local.panels;

import com.github.gwtbootstrap.client.ui.*;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryMapper;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.user.client.ui.Label;
import org.aplikator.client.shared.descriptor.ActionDTO;
import org.aplikator.client.shared.descriptor.MenuDTO;

import java.util.List;
import java.util.logging.Logger;

public class MenuPanel extends Modal {

    public interface MenuPanelResources extends ClientBundle {
        public static final MenuPanelResources INSTANCE = GWT.create(MenuPanelResources.class);

        @Source("MenuPanel.css")
        public MenuPanelCss css();
    }

    public interface MenuPanelCss extends CssResource {
        public String menuFrame();

        public String menuHeader();

        public String menuItem();

        public String menuBlock();

    }

    private static final Logger LOG = Logger.getLogger(MenuPanel.class.getName());

    private FluidContainer fluidContainer = new FluidContainer();

    private FluidRow fluidRow = new FluidRow();

    private Column basePanel = new Column(12);

    private PlaceController placeController;

    private PlaceHistoryMapper placeHistoryMapper;

    public MenuPanel() {
        super();
        fluidContainer.add(fluidRow);
        fluidRow.add(basePanel);
        add(fluidContainer);
        this.setTitle("Main menu");
        this.setAnimation(true);
        this.setKeyboard(true);
        basePanel.add(new Label("Loading menu"));// TODO localize
    }

    public void setMenus(List<MenuDTO> menus, PlaceController parplaceController, PlaceHistoryMapper parplaceHistoryMapper) {
        this.placeController = parplaceController;
        this.placeHistoryMapper = parplaceHistoryMapper;
        basePanel.clear();
        for (MenuDTO menu : menus) {
            basePanel.add(new Heading(2, menu.getLocalizedName()));
            for (final ActionDTO action : menu.getActions()) {
                Button actionButton = new Button();
                actionButton.setText(action.getLocalizedName());
                actionButton.setWidth("95%");
                actionButton.addClickHandler(new ClickHandler() {
                    @Override
                    public void onClick(ClickEvent event) {
                        MenuPanel.this.setAnimation(false);
                        MenuPanel.this.hide();
                        placeController.goTo(placeHistoryMapper.getPlace(action.getToken()));
                    }
                });
                basePanel.add(actionButton);
            }
        }
        LOG.finest("Loaded main menu.");
    }

}
